package com.mediacloud.app.newsmodule.fragment.ws


import android.content.DialogInterface
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.Color
import android.graphics.PixelFormat
import android.graphics.Typeface
import android.os.Build
import android.os.Bundle
import android.text.TextPaint
import android.text.TextUtils
import android.util.Log
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.WindowManager
import androidx.annotation.RequiresApi
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import androidx.viewpager.widget.ViewPager
import com.alibaba.fastjson.JSON
import com.donkingliang.consecutivescroller.ConsecutiveScrollerLayout
import com.eventTrack.CDPTrackReportManager
import com.eventTrack.TXReportManager
import com.github.gzuliyujiang.dialog.DialogColor
import com.github.gzuliyujiang.dialog.DialogConfig
import com.github.gzuliyujiang.wheelpicker.DatePicker
import com.github.gzuliyujiang.wheelpicker.annotation.DateMode
import com.github.gzuliyujiang.wheelpicker.entity.DateEntity
import com.github.gzuliyujiang.wheelpicker.impl.SimpleDateFormatter
import com.github.gzuliyujiang.wheelpicker.widget.DateWheelLayout
import com.mediacloud.app.assembly.adapter.IAdapterTitle
import com.mediacloud.app.assembly.util.isFastClick
import com.mediacloud.app.assembly.views.TimeLineRelativeLayout
import com.mediacloud.app.fbnavsk.navPaddingTopMatch
import com.mediacloud.app.model.component.ComponentItem
import com.mediacloud.app.model.interfaces.DataInvokeCallBack
import com.mediacloud.app.model.news.ArticleItem
import com.mediacloud.app.model.news.ArticleListData
import com.mediacloud.app.model.news.CatalogItem
import com.mediacloud.app.nav2.fragment.HqyNavFragment
import com.mediacloud.app.nav2.utils.DateUtils
import com.mediacloud.app.newsmodule.R
import com.mediacloud.app.newsmodule.adaptor.component.ComponentListItemStyleAdaptor
import com.mediacloud.app.newsmodule.adaptor.component.IExposure
import com.mediacloud.app.newsmodule.fragment.PagerAdapter
import com.mediacloud.app.newsmodule.fragment.baoliao.api.SpiderCmsApi
import com.mediacloud.app.newsmodule.model.MediaListBean
import com.mediacloud.app.newsmodule.utils.ComponentClickUtils
import com.mediacloud.app.newsmodule.utils.NewsItemClickUtils
import com.mediacloud.app.newsmodule.utils.NewsListDataInvoker
import com.mediacloud.app.quanzi.model.BaseDataListBean
import com.mediacloud.app.reslib.enums.Navigate
import com.mediacloud.app.reslib.enums.ToolBarActionF5OrTop
import com.mediacloud.app.reslib.enums.XKey
import com.mediacloud.app.util.ClickUtils
import com.scwang.smartrefresh.layout.api.RefreshFooter
import com.scwang.smartrefresh.layout.api.RefreshLayout
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener
import com.scwang.smartrefresh.layout.listener.SimpleMultiPurposeListener
import com.tencent.mmkv.MMKV
import com.utils.ExposurePoolService
import com.utils.NetUtils
import kotlinx.android.synthetic.main.fragment_ws24.*
import org.json.JSONArray
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import java.text.SimpleDateFormat
import java.time.DayOfWeek
import java.time.LocalDate
import java.time.format.DateTimeFormatter
import java.util.*


/**
 * 军情24小时
 */
class WS24Fragment : HqyNavFragment(), OnRefreshLoadMoreListener,
    DataInvokeCallBack<ArticleListData>, ToolBarActionF5OrTop, IExposure {
    val sdf1 = SimpleDateFormat("yyyy年MM月dd日", Locale.CHINA)
    val sdf2 = SimpleDateFormat("yyyyMMdd", Locale.CHINA)
    val sdf3 = SimpleDateFormat("yyyy-MM-dd", Locale.CHINA)
    val titles: ArrayList<String> = ArrayList()
    val fragments: ArrayList<Fragment> = ArrayList()
    var adapter: PagerAdapter? = null
    var catalogID: String? = null
    var hot_bg_img: String? = ""
    protected var catalogItem: CatalogItem? = null
    private var catalogs: MutableList<CatalogItem> = ArrayList()
    protected var dataInvoker: NewsListDataInvoker? = null
    var componentAdapter: ComponentListItemStyleAdaptor? = null
    var inited = false
    var hotData: MutableList<MediaListBean>? = null
    var hotTitle: HotMarqueeView? = null

    private lateinit var currentTask: Call<BaseDataListBean<MediaListBean>>

    private lateinit var pageChangeListener: ViewPager.OnPageChangeListener

    override fun getLayoutResID(): Int {
        return R.layout.fragment_ws24
    }

    var selectedTime: Long = System.currentTimeMillis()

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        navPaddingTopMatch()
    }

    override fun initArgs() {
        super.initArgs()
        if (fragmentArguments != null) {
            saveInstanceArguments = fragmentArguments
            catalogID = saveInstanceArguments?.getString("id")
            catalogItem = saveInstanceArguments?.getParcelable("catalog")
        } else if (saveInstanceArguments != null) {
            catalogID = saveInstanceArguments!!.getString("id")
            catalogItem = saveInstanceArguments!!.getParcelable("catalog")
        }
    }

    private fun getData() {
        dataInvoker?.getContentList(
            catalogID, 1, 1, null
        )
    }

    override fun choosed() {
        super.choosed()
        if (isAdded) {
            app_jhapp_home_subtab_content_imp()
        }
        if (fragments.size > 0){
            (fragments[0] as WS24ListFragment2).choosed()
        }

    }

    override fun unChosoed() {
        super.unChosoed()
        if (fragments.size > 0){
            (fragments[0] as WS24ListFragment2).unChoose()
        }
    }


    override fun initToRefresh() {
        if (activity == null || requireActivity().isFinishing || requireActivity().isDestroyed) {
            return
        }
        getHot()
        dataInvoker = NewsListDataInvoker(this)
        componentAdapter = ComponentListItemStyleAdaptor(requireContext(), catalogItem)
        getData()

    }

    var oldVerticalOffset: Int = 0
    override fun initView() {
        loadingView = findViewById(R.id.mLoadingView);
        initStateView()
        retryTips?.setOnClickListener {
            if (currentState != TYPE_LOADING) {
                showStateView(TYPE_LOADING, false)
                getHot()
                onRefresh(refreshLayout)
            }
        }
        album_collections?.setOnClickListener {
            if (isFastClick()) {
                TXReportManager.getInstance().app_jhapp_home_jq_tpics_clk()
//                Log.e("kang","--------------${articleListData?.navigates.toString()}-----------")
                val navigates = Navigate()
                navigates.id = "1306"
                navigates.name = "专题合集"
                navigates.category = "4"
                ComponentClickUtils.openNavigate(navigates, context, CatalogItem(), false, "专题合集")

            }
        }
        showStateView(TYPE_LOADING, false)
        refreshLayout.setOnRefreshLoadMoreListener(this)

        refreshLayout.setOnMultiPurposeListener(object : SimpleMultiPurposeListener() {
            override fun onFooterMoving(
                footer: RefreshFooter,
                isDragging: Boolean,
                percent: Float,
                offset: Int,
                footerHeight: Int,
                maxDragHeight: Int
            ) {
                scroller.stickyOffset = offset

            }

        })
//        adapter = PagerAdapter(fragments, titles, childFragmentManager)
//        viewpager.adapter = adapter
//        tabLayout.setViewPager(viewpager)

//        timeTv.text = sdf1.format(selectedTime)
        timeTv.setOnClickListener {
            TXReportManager.getInstance().app_jhapp_home_jq_date_clk()
            ClickUtils.delayClickable(it)
            showDatePicker()
        }
        openIv.setOnClickListener {
            TXReportManager.getInstance().app_jhapp_home_jq_date_clk()
            ClickUtils.delayClickable(it)
            showDatePicker()
        }
        pageChangeListener = object : ViewPager.OnPageChangeListener {
            override fun onPageScrolled(
                position: Int, positionOffset: Float, positionOffsetPixels: Int
            ) {
            }

            override fun onPageSelected(position: Int) {
                if (childFragmentManager.fragments[position] is WS24ListFragment2) {
                    val f = childFragmentManager.fragments[position] as WS24ListFragment2
                    f.preLoadKit?.let {
                        refreshLayout?.setNoMoreData(!it.hasMore)
                    }
                    if (selectedTime != f.group_date_time) {
                        selectedTime = f.group_date_time
                        timeTv.text = f.group_date_time_fromat
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                            tvWeek.text = DateUtils.getDayOfWeek(f.group_date_time_fromat,"yyyy.MM.dd")
                        }
                    }
                }
                onThirdChannelTabEvent(position)
            }

            override fun onPageScrollStateChanged(state: Int) {
            }
        }

        viewpager.addOnPageChangeListener(pageChangeListener);
        scroller.onVerticalScrollChangeListener =
            ConsecutiveScrollerLayout.OnScrollChangeListener { v, scrollY, oldScrollY, scrollState ->
                if (scrollState == ConsecutiveScrollerLayout.OVER_SCROLL_ALWAYS) {
                    app_jhapp_home_subtab_content_imp()
                }

            };
    }

    fun changeDate() {
        val f = childFragmentManager.fragments[viewpager.currentItem] as WS24ListFragment2
        if (selectedTime != f.group_date_time) {
            selectedTime = f.group_date_time
            if (f.group_date_time_fromat != timeTv.text.toString()) {
                timeTv.text = f.group_date_time_fromat
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                    tvWeek.text = DateUtils.getDayOfWeek(f.group_date_time_fromat,"yyyy.MM.dd")
                }
            }
        }
    }

    var picker: DatePicker? = null
    var hasDarkMask: Boolean = false;
    private fun showDatePicker() {
        if (picker == null) {

            val dialogColor = DialogColor()
            val cctv7Color = resources.getColor(R.color.cctv7_red_light)
            dialogColor.topLineColor(Color.parseColor("#f8f8f8"))
            dialogColor.titleTextColor(Color.parseColor("#222222"))
            dialogColor.cancelTextColor(Color.parseColor("#999999"))
            dialogColor.okTextColor(cctv7Color)
            DialogConfig.setDialogColor(dialogColor)
            picker = object : DatePicker(requireActivity()) {
                override fun createBodyView(): View {
                    wheelLayout = object : DateWheelLayout(activity) {
                        override fun provideLayoutRes(): Int {
                            return R.layout.ws_wheel_picker_date
                        }
                    }

                    return wheelLayout
                }

                override fun onDismiss(dialog: DialogInterface?) {
                    super.onDismiss(dialog)
                    //view被销毁后就不要持有了，否则会内存泄漏
                    maskView = null
                }
            }
            picker!!.setTitle("日期选择")
            picker!!.titleView.textSize = 17f
            picker!!.titleView.typeface = Typeface.DEFAULT_BOLD
            picker!!.cancelView.textSize = 15f
            picker!!.cancelView.text = "取消"
            picker!!.okView.textSize = 15f
            picker!!.okView.text = "确定"

            val wheelLayout: DateWheelLayout = picker!!.wheelLayout


            wheelLayout.setDateFormatter(SimpleDateFormatter())
            wheelLayout.setDateMode(DateMode.YEAR_MONTH_DAY)

            val calendar = Calendar.getInstance()
            val year = calendar.get(Calendar.YEAR)
            val month = calendar.get(Calendar.MONTH)
            val day = calendar.get(Calendar.DAY_OF_MONTH)
            val target = DateEntity.target(Date(selectedTime))
            wheelLayout.setRange(
                DateEntity.target(1900, 1, 1),
                DateEntity.target(year + 20, month + 1, day),
                target
            );

            //wheelLayout.setRange(DateEntity.target(2021, 1, 1), DateEntity.target(2050, 12, 31), DateEntity.today());
            // wheelLayout.setRange(DateEntity.today(), DateEntity.monthOnFuture(3))
//        wheelLayout.setCurtainEnabled(true)


            wheelLayout.setIndicatorColor(Color.WHITE)
            wheelLayout.setIndicatorSize(resources.displayMetrics.density * 2)
            wheelLayout.setTextColor(Color.BLACK)
            wheelLayout.setTextSize(14 * resources.displayMetrics.scaledDensity)
            //注：建议通过`setStyle`定制样式设置文字加大，若通过`setSelectedTextSize`设置，该解决方案会导致选择器展示时跳动一下
            //wheelLayout.setSelectedTextSize(16 * getResources().getDisplayMetrics().scaledDensity);
            //注：建议通过`setStyle`定制样式设置文字加大，若通过`setSelectedTextSize`设置，该解决方案会导致选择器展示时跳动一下
            //wheelLayout.setSelectedTextSize(16 * getResources().getDisplayMetrics().scaledDensity);
            wheelLayout.setSelectedTextColor(cctv7Color)
            wheelLayout.yearLabelView.setTextColor(cctv7Color);
            wheelLayout.monthLabelView.setTextColor(cctv7Color);
            wheelLayout.yearLabelView.setTextColor(cctv7Color);

            picker!!.setOnDatePickedListener { year, month, day ->
                if (activity == null || requireActivity().isFinishing || requireActivity().isDestroyed || isDetached || isRemoving) {
                    return@setOnDatePickedListener
                }
                val selectedTime = sdf2.parse(
                    "$year${String.format("%02d", month)}${
                        String.format(
                            "%02d", day
                        )
                    }"
                )?.time ?: 0L
                //   timeTv.text = sdf1.format(selectedTime)
                val d = sdf3.format(selectedTime)
                TXReportManager.getInstance()
                    .app_jhapp_home_jq_date_sbm("$year", "$month", "$day", "成功", "")
                val intent = Intent(context, WS24FilterActivity::class.java)
                val item = if (viewpager.currentItem < catalogs.size) {
                    catalogs.get(viewpager.currentItem)
                } else {
                    CatalogItem()
                }
                wheelLayout.setDefaultValue(DateEntity.today())
                wheelLayout.postDelayed({
                    if (activity == null || requireActivity().isFinishing || requireActivity().isDestroyed) {
                        return@postDelayed
                    }
                    intent.putExtra("NAV_ID", item.catid)
                    intent.putExtra("CATALOG", item)
                    intent.putExtra("DATE", d)
                    startActivity(intent)
                }, 300)
            }

            picker!!.setOnDismissListener {
                openIv.animate().rotation(0f)
            }
            val endTime = (sdf1.parse("${year}年${month + 1}月${day}日")?.time ?: 0L) + 3600000 * 24
            wheelLayout.setOnDateSelectedListener { year, month, day ->

                val time = sdf2.parse(
                    "$year${String.format("%02d", month)}${
                        String.format(
                            "%02d", day
                        )
                    }"
                )?.time ?: 0L

                if (time >= endTime) {
                    wheelLayout.setDefaultValue(DateEntity.today())
                }
            }
            picker!!.wheelLayout.setResetWhenLinkage(false)

            picker!!.setBackgroundDrawable(
                ContextCompat.getDrawable(
                    requireContext(), R.drawable.round_top_shape
                )
            )

            //通用Dialog夜间模式
            if (MMKV.defaultMMKV().getBoolean(XKey.DARK_MODE, false)) {
                showDialogDarkMask { lp, mask ->
                    hasDarkMask = true;
                    picker?.addContentView(mask, lp)
                }
            }
        }


        if (MMKV.defaultMMKV().getBoolean(XKey.DARK_MODE, false)) {
            picker?.findViewById<ConstraintLayout>(R.id.dark_mask)?.visibility = View.VISIBLE
        } else {
            dissmissDialogDarkMask();
        }

        openIv.animate().rotation(180f)
        picker?.show()
    }

    class TitleImp(val title: String) : IAdapterTitle {

        override fun getTitle(): CharSequence {
            return title
        }
    }

    override fun onRefresh(refreshLayout: RefreshLayout) {
        TimeLineRelativeLayout.headList.clear()
        getData()
    }

    override fun onLoadMore(refreshLayout: RefreshLayout) {
        if (fragments.isEmpty()) {
            refreshLayout.finishLoadMore()
            return
        }
        val index = viewpager.currentItem
        val f = childFragmentManager.fragments[index]
        if (f is OnLoadMoreListener) {
            f.onLoadMore(refreshLayout)
        }
    }


    private fun topCrop(srcBitmap: Bitmap, desWidth: Int, desHeight: Int): Bitmap? {
        val srcWidth = srcBitmap.width
        val srcHeight = srcBitmap.height
        var newWidth = srcWidth
        var newHeight = srcHeight
        val srcRate = srcWidth.toFloat() / srcHeight
        val desRate = desWidth.toFloat() / desHeight
        var dx = 0
        var dy = 0
        if (srcRate == desRate) {
            return srcBitmap
        } else if (srcRate > desRate) {
            newWidth = (srcHeight * desRate).toInt()
            dx = (srcWidth - newWidth) / 2
        } else {
            newHeight = (srcWidth / desRate).toInt()
            dy = 0
            //   dy = (srcHeight - newHeight) / 2
        }
        //创建目标Bitmap，并用选取的区域来绘制
        return Bitmap.createBitmap(srcBitmap, dx, dy, newWidth, newHeight)
    }

    var articleListData: ArticleListData? = null

    @RequiresApi(Build.VERSION_CODES.LOLLIPOP)
    override fun success(data: ArticleListData?) {
        if (activity == null || requireActivity().isFinishing || requireActivity().isDestroyed) {
            return
        }

        MMKV.defaultMMKV().putString(XKey.CACHE_WS24_TAB+catalogID, JSON.toJSONString(data))
        articleListData = data
        refreshLayout.finishRefresh()
        var c999968: ComponentItem? = null
        componentContainer.reset()
        if (data?.state == true) {
            val componentItems = data.componentItems
            if (componentItems != null) {
                componentAdapter?.listContentData = componentItems
                componentAdapter?.clearEvent()
                for (i in 0 until componentItems.size) {
                    val item = componentItems[i]
                    if (item.widget == 999968) {
                        c999968 = item
                        break
                    } else {
                        val view =
                            componentAdapter?.getView(i, null, componentContainer) ?: continue
                        componentContainer.addView(view)
                    }
                }
                //安徽业务暂时屏蔽
               // addHotView()
                c999968?.let {
                    val other_field = it.orginDataObject.optJSONObject("other_field")
                    val bg_img = other_field?.optString("bg_img")
                    hot_bg_img = other_field?.optString("hot_bg_img")
                    buildTab(it)
                }
            }


            /*if (componentAdapter?.listContentData == null || componentAdapter?.listContentData?.size == 0) {
                showStateView(TYPE_NO_CONTENT, false)
            } else {
                closeStateView()
            }*/
        } else {
            //showStateView(TYPE_NO_CONTENT, false)
        }
        //没数据没网  展示无网络提醒
        if (!NetUtils.isNetConnection(context)&&(componentAdapter?.listContentData == null || componentAdapter?.listContentData?.size == 0)){
            showStateView(TYPE_NET_NOT_GIVE_FORCE, false)
        } else if (componentAdapter?.listContentData == null || componentAdapter?.listContentData?.size == 0) {
            showStateView(TYPE_NO_CONTENT, false)
        } else {
            closeStateView()
        }
//        componentContainer.removeAllViews()
//        val v = View(requireContext())
//        v.setBackgroundColor(Color.YELLOW)
//        componentContainer.addView(v,-1,Utility.dpToPx(requireContext(),200f))
//        setBackGround("https://img1.baidu.com/it/u=1119512571,3451633790&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=889")
//        titles.clear()
//        fragments.clear()
//        titles.add("国内")
//        titles.add("国外")
//        fragments.add(WS24ListFragment.newInstance(""))
//        fragments.add(WS24ListFragment.newInstance(""))
//        adapter?.notifyDataSetChanged()

    }

    override fun fault(data: Any?) {
        if (activity == null || requireActivity().isFinishing || requireActivity().isDestroyed) {
            return
        }
        refreshLayout.finishRefresh(false)
        closeStateView()


        val cache  = MMKV.defaultMMKV().getString(XKey.CACHE_WS24_TAB+catalogID,"")
        if (!TextUtils.isEmpty(cache)){
            val data = JSON.parseObject(cache, ArticleListData::class.java)
            success(data)
        }else{
            if (!NetUtils.isNetConnection(context) && (componentAdapter?.listContentData == null || componentAdapter?.listContentData?.size == 0)) {
                showStateView(TYPE_NET_NOT_GIVE_FORCE, false)
            } else if (componentAdapter?.listContentData == null || componentAdapter?.listContentData?.size == 0) {
                showStateView(TYPE_NO_CONTENT, false)
            } else {
                closeStateView()
            }
        }
    }


    private fun addHotView() {

        val hotView =
            LayoutInflater.from(requireContext()).inflate(R.layout.item_ws_24_hot, null, false)
        componentContainer.addView(hotView, -1, resources.getDimensionPixelSize(R.dimen.dimen50))
        componentContainer.notifyDataSetChanged()
        hotTitle = hotView.findViewById(R.id.hotTitle)

        hotData?.let {
            setHotData()
        }

        //val hotOpen = hotView.findViewById<View>(R.id.hotOpen)
        val hotAll = hotView.findViewById<View>(R.id.hotAll)
        hotAll.setOnClickListener {

            if (isFastClick()) {
                val intent = Intent()
                intent.putExtra("HOT_BG_IMG", hot_bg_img)
                intent.setClassName(
                    requireContext(),
                    "com.mediacloud.app.appfactory.activity.search.HotRankActivity"
                )
                requireContext().startActivity(intent)
            }

        }


    }

    val catids: MutableList<String> = ArrayList()
    private fun buildTab(componentItem: ComponentItem) {

        val element = componentItem.getElement()
        val tempCatalogs: MutableList<CatalogItem> = ArrayList()
        val tempCatIds: MutableList<String> = ArrayList()
        try {
            val jsonArray = JSONArray(element)
            val length = jsonArray.length()
            for (i in 0 until length) {
                jsonArray.optJSONObject(i)?.let { nav ->
                    val item = CatalogItem()
                    item.catid = nav.optString("nid")
                    item.catname = nav.optString("title", "")
                    tempCatalogs.add(item)
                    tempCatIds.add(item.catid)
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }

        if (catids.size != 0 && catids.containsAll(tempCatIds)) {
            childFragmentManager.fragments.forEach {
                (it as WS24ListFragment2).refresh()
            }
        } else {
            catids.clear()
            catids.addAll(tempCatIds)
            titles.clear()
            fragments.clear()
            catalogs.clear()
            catalogs.addAll(tempCatalogs)
            catalogs.forEach {
                val f = WS24ListFragment2.newInstance(it.catid, it/*, d*/)
                f.refreshLayout = refreshLayout
                f.cacheCatalogID = catalogID
                titles.add(it.catname)
                fragments.add(f)
            }
            if (titles.size > 1) {
                tabLayout.visibility = View.VISIBLE
            } else {
                tabLayout.visibility = View.GONE
            }
            if (viewpager.adapter == null) {
                viewpager.adapter = PagerAdapter(fragments, titles, childFragmentManager)
                tabLayout.setViewPager(viewpager)
            }
            tabLayout.currentTab = 0
            //viewpager.adapter?.notifyDataSetChanged()
            tabLayout.notifyDataSetChanged()
            onThirdChannelTabEvent(tabLayout?.currentTab ?: 0)
        }

    }


    fun onThirdChannelTabEvent(position: Int) {

    }

    override fun onResume() {
        super.onResume()
    }

    override fun onPause() {
        super.onPause()
    }

    //    fun getElementList(element: JSONArray?, componentItem: ComponentItem?): MutableList<ArticleItem> {
//        val list: MutableList<ArticleItem> = ArrayList()
//        try {
//            element?.let {
//                for (i in 0 until it.length()) {
//                    it.optJSONObject(i)?.let {
//                        val item = ArticleItem.parse(it)
//                        componentItem?.let {
//                            if (it.mShowSwitch == null) {
//                                it.orginDataObject?.optJSONObject("show_switch")?.let {
//                                    componentItem.mShowSwitch?.allowShowHitCount = it.optInt("show_hit_count", 0) == 1
//                                    componentItem.mShowSwitch?.allowShowInteractionCount = it.optInt("show_interaction_count", 0) == 1
//                                    componentItem.mShowSwitch?.allowShowPublishDate = it.optInt("show_publish_date", 0) == 1
//                                    componentItem.mShowSwitch?.allowShowSource = it.optInt("show_source", 0) == 1
//                                    componentItem.mShowSwitch?.allowShowComment = it.optInt("show_comment", 0) == 1
//                                }
//                                if (it.mShowSwitch == null) {
//                                    componentItem.mShowSwitch = ShowSwitch()
//                                    componentItem.mShowSwitch?.allowShowHitCount = GlobalSwitch.allowShowHitCount
//                                    componentItem.mShowSwitch?.allowShowInteractionCount = GlobalSwitch.allowShowInteractionCount
//                                    componentItem.mShowSwitch?.allowShowPublishDate = GlobalSwitch.allowShowPublishDate
//                                    componentItem.mShowSwitch?.allowShowSource = GlobalSwitch.allowShowSource
//                                    componentItem.mShowSwitch?.allowShowComment = GlobalSwitch.allowShowComment
//                                }
//                            }
//                            item.mShowSwitch = componentItem.mShowSwitch
//                        }
//
//                        item.logo = it.optString("logo")
//                        item.cmsCustomStyle = null
//                        list.add(item)
//                    }
//                }
//            }
//        } catch (e: java.lang.Exception) {
//            e.printStackTrace()
//        }
//        return list
//    }
    private fun getHot() {
        if (context == null) {
            return
        }
        if (isDetached() || isDispose() || isRemoving()) {
            return
        }

        currentTask = SpiderCmsApi.getSpiderCmsApi(context).getSpiderHotArticle(
            "5", 1, 10, requireContext().resources?.getString(R.string.tenantid)
        )

        currentTask.enqueue(object : Callback<BaseDataListBean<MediaListBean>> {
            override fun onResponse(
                call: Call<BaseDataListBean<MediaListBean>>,
                response: Response<BaseDataListBean<MediaListBean>>
            ) {
                if (activity == null || requireActivity().isFinishing || requireActivity().isDestroyed) {
                    return
                }
                if (isDetached() || isDispose() || isRemoving()) {
                    return
                }
                if (response.body()?.isSuccess == true) {
                    val data = response.body()?.data?.pageRecords
                    data?.let {
                        if (data.isNotEmpty()) {
                            hotData = data
                            hotTitle?.let {

                                setHotData()
                            }
                        }
                    }
                }
            }

            override fun onFailure(call: Call<BaseDataListBean<MediaListBean>>, t: Throwable) {

            }
        })
    }

    var hotClickData: MutableList<MediaListBean>? = null
    private fun setHotData() {
        val hotList: MutableList<HotMarqueeView.ItemData> = ArrayList()
        var textsize: Float = mActivity?.resources?.getDimension(R.dimen.dimen15)!!
        if (hotClickData == null) {
            hotClickData = ArrayList()
        } else {
            hotClickData?.clear()
        }
        hotTitle?.post {

            hotData?.let {
                try {
                    val w: Int =
                        (hotTitle!!.width - mActivity?.resources?.getDimension(R.dimen.dimen21)!!).toInt()
                    var textPaint = TextPaint()
                    textPaint.setTextSize(textsize)
                    var item: HotMarqueeView.ItemData? = null
                    for (i in 0 until it.size) {
                        // hotList.add("${i + 1}.${hotData?.get(i)?.title}")
                        if (hotData?.get(i) != null && !TextUtils.isEmpty(hotData?.get(i)?.title)) {
                            val title = hotData?.get(i)?.title + ""
                            var length = textPaint.measureText(title)

                            if (length > 0f && w > 0 && title.length > 0 && length > w) {
                                var endIndex = (title.length * w / length).toInt()
                                endIndex = getEndIndex(textPaint, endIndex, title, w)

                                item = HotMarqueeView.ItemData(
                                    i, title.substring(0, endIndex), true, i == 0
                                )
                                hotList.add(item)
                                item = HotMarqueeView.ItemData(
                                    i, title.substring(endIndex, title.length), false, i == 0
                                )
                                hotList.add(item)
                                hotClickData?.add(hotData?.get(i)!!)
                                hotClickData?.add(hotData?.get(i)!!)
                            } else {
                                item = HotMarqueeView.ItemData(i, title, true, i == 0)
                                hotList.add(item)
                                hotClickData?.add(hotData?.get(i)!!)
                            }
                            /*if (title.length>max){
                                    hotList.add(title.substring(0, (max).toInt()))
                                    hotList.add(title.substring((max).toInt(),title.length ))
                                    hotClickData?.add(hotData?.get(i)!!)
                                    hotClickData?.add(hotData?.get(i)!!)
                                }else{
                                    hotList.add(title)
                                    hotClickData?.add(hotData?.get(i)!!)
                                }*/

                        }

                    }
                    hotTitle?.startWithList(hotList)
                } catch (e: Exception) {

                }
            }

        }

        hotTitle?.setOnItemClickListener { position, textView ->
            try {
                hotClickData?.let {
                    val hto = it[position]
                    val item = ArticleItem()
                    item.id = hto.id
                    item.type = hto.resourceType
                    item.title = hto.title
                    item.positionInList = position
                    NewsItemClickUtils.OpenItemNewsHandle(
                        requireContext(), item.type, item, CatalogItem()
                    )
                    if (TXReportManager.getInstance().firstTabInfo.tabName == "首页") {
                        TXReportManager.getInstance().app_jhapp_home_subtab_content_interact(
                            "点击查看详情",
                            "军情顶部滚动组件",
                            "",
                            "",
                            "",
                            "",
                            "",
                            "",
                            item
                        )
                    }

                }
            } catch (e: Exception) {

            }

        }
    }

    private fun getEndIndex(tp: TextPaint, end: Int, title: String, width: Int): Int {
        var endIndex = end
        while (endIndex < title.length) {
            if (endIndex + 1 < title.length
                && tp.measureText(title.substring(0, endIndex + 1)) < width)
            {
                endIndex = endIndex + 1
            } else {
                return endIndex
            }

        }
        return endIndex
    }

    override fun onDestroyView() {
        currentTask.cancel()
        componentAdapter?.clearEvent()
        if (picker != null) {
            picker?.cancel()
            picker = null
        }
        hotTitle?.setOnItemClickListener(null)
        dataInvoker?.destory()

        if (childFragmentManager.fragments != null && childFragmentManager.fragments.isEmpty()) {
            for (fragment in childFragmentManager.fragments) {
                fragment.onDestroyView()
                fragment.onDestroy()
            }
        }


        viewpager.removeOnPageChangeListener(pageChangeListener)
        if (fragments != null && fragments.isNotEmpty()) {
            for (it in fragments) {
                it.onDetach()
                it.onDestroyView()
                it.onDestroy()
            }
            fragments.clear()
        }

        super.onDestroyView()
    }

    override fun f5() {
        //  scroller.scrollY = 0

        scroller.scrollToChild(scroller.getChildAt(0))
        refreshLayout.setEnableRefresh(true)
        refreshLayout.autoRefresh(200)
    }

    override fun gun() {
        //  scroller.scrollY = 0
        scroller.scrollToChild(scroller.getChildAt(0))
    }

    fun night(windowManager: WindowManager, view: View?) {
        val lp = WindowManager.LayoutParams(
            WindowManager.LayoutParams.MATCH_PARENT,
            WindowManager.LayoutParams.FLAG_FULLSCREEN,
            WindowManager.LayoutParams.TYPE_APPLICATION,
            WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE or WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
            PixelFormat.TRANSLUCENT
        )

        //StatusBarUtil.setColor(this,Color.BLACK,255);
        lp.gravity = Gravity.BOTTOM // 可以自定义显示的位置
        lp.x = 0
        lp.y = 0
        windowManager.addView(view, lp)
    }

    private var dataReady = false
    private val app_jhapp_home_subtab_content_impRunable: Runnable = Runnable {
        ExposurePoolService.getExecutorService().execute {


            try {
                val position = viewpager.currentItem ?: 0
                val fragment: Fragment? = childFragmentManager.fragments[position]

                if (fragment != null && fragment is IExposure) {
                    val articleItemList = (fragment as IExposure).exposureArticles
                    articleItemList?.let {
                        for (i in 0 until articleItemList.size) {
                            val article = articleItemList[i]
                            article.positionInList = i
                            CDPTrackReportManager.getInstance().NewsRPExpose(i,article)
                            TXReportManager.getInstance().app_jhapp_home_subtab_content_imp(
                                article,
                                null,
                                catalogItem
                            )
                        }
                    }
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }

    private fun app_jhapp_home_subtab_content_imp() {
        if (!dataReady) return
        scroller?.apply {
            removeCallbacks(app_jhapp_home_subtab_content_impRunable)
            postDelayed(app_jhapp_home_subtab_content_impRunable, TXReportManager.EXPOSURE_DELAY)
        }
    }

    //用于子fragment的回调
    override fun getExposureArticles(): MutableList<ArticleItem>? {
        dataReady = true
        if (hadChoosed) {
            app_jhapp_home_subtab_content_imp()
        }
        return null
    }

    override fun getExposureComponentItem(): ComponentItem? {
        return null
    }
}